<?php
/*
 * Copyright notice
 * 
 * (c) 2009 MH-Dev.de, Martin Hesse <info@mh-dev.de>
 * 
 * This script is part of the MH-Dev.-Board project. The MH-Dev.-Board 
 * is free software; you can redistribute it and/or modify it under the 
 * terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, 
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty 
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU 
 * General Public License along with this program; if not, 
 * see http://www.gnu.org/licenses/.
 */


/**
 * PostsController
 * 
 * Get posts from a thread
 * 
 * @author	Martin Hesse <info@mh-dev.de>
 * @package	MH-Dev.-Board
 */
class PostsController extends Zend_Controller_Action
{
	private $registry; // registry
	private $auth; // user-values
	private $settings; // board-settings
	private $translate; // translation
	
	public function init()
	{		
		// registry
		$this->registry = Zend_Registry::getInstance();
		
		// settings
		$this->settings	= $this->registry->get('settings');
		
		// auth
		$auth = Zend_Auth::getInstance();
    	$this->view->auth = $auth->hasIdentity();
    	
    	if($auth->hasIdentity())
    	{
    		$this->view->auth_role 			= $auth->getIdentity()->role;
    		$this->view->username 			= $auth->getIdentity()->username;
    		$this->view->auth_uid			= $auth->getIdentity()->uid;
    		$this->view->unread_messages	= $auth->getIdentity()->count_unread_messages;
    		$this->view->posts_rating		= $auth->getIdentity()->posts_rating;
    	}
    	else
    	{
    		$this->view->username 	= 'Gast';
    	}

    	$this->auth = $auth;
    	
    	// lang
		$this->translate = $this->registry->get('lang');
		$this->view->translate = $this->translate;
		
		// flash messenger
		$this->view->flashMessenger	= $this->_helper->FlashMessenger;
		
		// include jquery
		$baseurl = new MHDEV_View_Helper_BaseUrl();
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/css/default/jquery.css');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/jquery-1.3.2.min.js');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/jquery-ui-1.7.2.custom.min.js');
	}
	
	
	/*
	 * Index
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function indexAction()
	{
		// BBCode-Editor
		$this->initEditor();
		
		// params
		$uid 		= intval($this->getRequest()->getParam('uid', 0));
		$page 		= intval($this->getRequest()->getParam('page', 0));
		$count		= $this->auth->hasIdentity() ? $this->auth->getIdentity()->posts_per_page : $this->settings['posts_per_page']; 
		
		// vars
		$user_uid	= @$this->auth->getIdentity()->uid;
		$pubPosts	= 0;
		$move_topic	= false;
		
		// update Visit-Status
		$this->updateVisit($uid);
		
		// observe thread, update "watching"-status ...
		if($this->auth->hasIdentity()) { $this->observeThread($uid); }
		
		// helper
		$baseUrl 	= new MHDEV_View_Helper_BaseUrl();
		$mod		= new MHDEV_View_Helper_IsMod();
		
		// db
		$posts		= new Posts();
		$threads	= new Threads();
		$boards		= new Boards();
		$categories	= new Categories();
		
		// update hits+1
		$threads->update(array('count_hits' => new Zend_Db_Expr('count_hits+1')), 'uid=' . $uid);
		
		if($user_uid)
		{
			$getPubPosts	= $posts->fetchAll('is_public = 1 AND user_uid =' . $user_uid);
			$pubPosts		= $getPubPosts->count();
		}
			
		// form
		$new_post	= new NewPostForm();
		
		// query
		$select = $posts->select()->setIntegrityCheck(false);
		$select->from(
				array('p' => 'posts')
			)
			->join(
				array('u' => 'user'), 'u.uid = p.user_uid', array('username', 'count_threads', 'count_posts', 'signature')
			)
			->join(
				array('t' => 'threads'), 't.uid = p.thread_uid', array('is_deleted AS tdeleted')
			)
			->where('p.thread_uid = ?', $uid)
			->order('p.create_date ASC');
		
		// filter
		if(!$this->auth->hasIdentity() OR $this->auth->getIdentity()->role != 'admin')
		{
			$select->where('p.is_deleted = ?', 0);
			$select->where('t.is_deleted = ?', 0);
			$select->where('p.is_public = ?', 1);
		}
		
		$query		= $posts->fetchAll($select, null, $count);
		
		$getThread	= $threads->find($uid);
		
		if($getThread->count() > 0)
		{
			$arrayThread			= $getThread->toArray();
			$this->view->board_uid	= $arrayThread[0]['board_uid'];
			$this->view->closed		= $arrayThread[0]['is_closed'];
			$this->view->sticky		= $arrayThread[0]['is_sticky'];
			$this->view->deleted	= $arrayThread[0]['is_deleted'];
			$this->view->title		= $arrayThread[0]['title'];
			$this->view->author_uid	= $arrayThread[0]['user_uid'];
			
			if($arrayThread[0]['moved_uid'] > 0)
			{
				$this->_redirect('/posts/' . $arrayThread[0]['moved_uid'] . '.html');
			}
			
			// move topic form
			if($this->auth->hasIdentity() && $mod->IsMod($this->auth->getIdentity()->uid, $arrayThread[0]['board_uid']))
			{
				// set status to true
				$move_topic					= true;
				
				// query
				$getCategories 				= $categories->fetchAll();
				
				// view
				$this->view->cats_count 	= $getCategories->count();
				$this->view->cats_res		= $getCategories->toArray();
			}
			
			$getGuestPerm			= $boards->find($arrayThread[0]['board_uid']);
			
			if($getGuestPerm->count() > 0)
			{
				$arrayGuestPerm = $getGuestPerm->toArray();
				$this->view->allow_guest_posts 	= $arrayGuestPerm[0]['allow_guest_posts'];
				$this->view->is_public			= $arrayGuestPerm[0]['is_public'];
				
				// add captcha-field to non-registered-user
				if(!$this->auth->hasIdentity() && $arrayGuestPerm[0]['allow_guest_posts'] == 1)
				{
					$captcha = new Zend_Form_Element_Captcha('captcha', array(
			            'label' => $this->translate->_('captcha'),
			            'captcha' => array(
			                'captcha' => 'Image',
			                'wordLen' => 6,
			                'timeout' => 300,
			                'width' => 200,
			                'heigth' => 150,
			                'imgDir' => 'static/gfx/captcha/',
			                'imgUrl' => $baseUrl->BaseUrl() . '/static/gfx/captcha/',
			                'font' => 'static/gfx/captcha/fonts/gautami.ttf',
			                'fontsize' => 28,
			        		'messages' => array(
			                    'badCaptcha' => $this->translate->_('error_captcha'),
			                    'missingID' => $this->translate->_('error_captcha'),
			                    'missingValue' => $this->translate->_('error_captcha')
			                )
			            )
			        ));
			        
			        $new_post->addElement($captcha, 'captcha', array('order' => 2));			        
			        $this->view->captcha = $new_post->getElement('captcha');
				}
			}
		}
		
		// paginator
		$paginator	= Zend_Paginator::factory($query->toArray());
        $paginator->setItemCountPerPage($count);
        $paginator->setCurrentPageNumber($page);
        
		// view
		$this->view->result_count	= $query->count();
		$this->view->result			= $paginator;
		$this->view->thread_uid		= $uid;
		$this->view->form			= $new_post;
		$this->view->pubPosts		= $pubPosts;
		$this->view->allowRating	= $this->settings['allow_rating'];
		$this->view->move_topic		= $move_topic;
		
		// get post data
		if($this->_request->isPost() && $new_post->isValid($_POST))
		{
			if($post_uid = $this->newPost($new_post, $uid, $pubPosts))
			{
				$this->_redirect('/posts/' . $uid . '-' . $this->getPageNumber($uid) . '.html#post' . $post_uid);	
			}
			else
			{
				$new_post->populate($_POST);
			}
		}
		else
		{
			$new_post->populate($_POST);
		}
	}
	
	
	/*
	 * Creates a new post in the database
	 * 
	 * @param Zend_Form $form
	 * @param int $uid
	 * @param int $pubPosts
	 * 
	 * return boolean on success true otherwhise false
	 */
	public function newPost($form, $uid, $pubPosts)
	{
		// db
		$posts 		= new Posts();
		$user		= new User();
		$threads	= new Threads();
		$boards		= new Boards();
		
		//form
		$values		= $form->getValues();
		$user_uid	= $this->auth->getIdentity()->uid > 0 ? $this->auth->getIdentity()->uid : 0;

		$newPostArray	= array(
			'thread_uid'	=> $uid,
			'user_uid'		=> $user_uid,
			#'title'		=> trim($values['title']),
			'text'			=> $values['text'],
			'smilies'		=> intval($values['smilies']),
			'create_date'	=> new Zend_Db_Expr("NOW()"),
		);
		
		// if this user have a public post before
		if($pubPosts > 0)
		{
			// then set this post public
			$newPostArray['is_public'] = 1;
		}
		
		if($post_uid = $posts->insert($newPostArray))
		{
			// if user is logged in ...
			if($this->auth->hasIdentity())
			{
				// update activity points and post count
				$this->activityPoints();
				$userUpdateArray = array('count_posts' => new Zend_Db_Expr('count_posts+1'));
				$user->update($userUpdateArray,'uid=' . $user_uid);
			}
			
			// set thread replies +1
			$threadUpdateArray 	= array(
				'last_reply_date'		=> new Zend_Db_Expr('NOW()'),
				'last_reply_user_uid'	=> $user_uid,
				'count_replies'			=> new Zend_Db_Expr('count_replies+1')
			);
			$threads->update($threadUpdateArray, 'uid=' . $uid);
			
			// set board replies +1 and the last post / thread uid
			$getBoard	 	= $threads->find($uid);
			$getBoardArray	= $getBoard->toArray();
			
			$boardUpdateArray	= array(
				'last_post_uid'		=> $post_uid,
				'last_thread_uid'	=> $uid,
				'count_posts'		=> new Zend_Db_Expr('count_posts+1')
			);
			$boards->update($boardUpdateArray, 'uid=' . $getBoardArray[0]['board_uid']);
			
			// check if board is a sub board
			$rootCheck	= $boards->find($getBoardArray[0]['board_uid']);
			if($rootCheck->count() > 0)
			{
				// array with database results
				$arrayRootCheck = $rootCheck->toArray();
				
				// have a root uid?
				if($arrayRootCheck[0]['root_uid'] > 0)
				{
					// update root board
					$boards->update($boardUpdateArray, 'uid =' . $arrayRootCheck[0]['root_uid']);
				}
			}
			
			return $post_uid;
		}
		else
		{
			return false;
		}
	}
	
	
	
	/*
	 * Edit a post
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function editAction()
	{
		// BBCode-Editor
		$this->initEditor();
		
		// post
		$postData	= $this->_request->getPost();
		
		// param
		$uid 		= intval($this->_request->getParam('uid', 0));
		
		// helper
		$url		= new Zend_View_Helper_Url();
		$baseUrl	= new MHDEV_View_Helper_BaseUrl();
		$isMod		= new MHDEV_View_Helper_IsMod();
		
		// db
		$posts		= new Posts();
		$threads	= new Threads();
		
		// form
		$form		= new NewPostForm();
		
		// query
		$query		= $posts->find($uid);
		
		if($query->count() > 0)
		{
			$res = $query->toArray();
			
			$getTopic 	= $threads->find($res[0]['thread_uid']);
			$resTopic 	= $getTopic->toArray(); 
			
			if(
				$this->auth->hasIdentity() && 
				$this->auth->getIdentity()->uid == $res[0]['user_uid'] OR 
				$isMod->IsMod($this->auth->getIdentity()->uid, $resTopic[0]['board_uid'])
			) 
			{
				if($this->_request->isPost() && $form->isValid($postData))
				{
					$values = $form->getValues();
					
					$postUpdateArray = array(
						'text'			=> $values['text'],
						'smilies'		=> intval($postData['smilies']),
						'edit_date'		=> new Zend_Db_Expr('NOW()'),
						'count_edit'	=> new Zend_Db_Expr('count_edit+1')
					);
					
					if($posts->update($postUpdateArray, 'uid=' . $uid))
					{
						$this->_redirect('/posts/' . $res[0]['thread_uid'] . '-' . $this->getPageNumber($res[0]['thread_uid']) . '.html#post' . $uid);
					}
				}
				else
				{
					$this->view->thread_uid = $res[0]['thread_uid'];
					$this->view->text 		= $res[0]['text'];
					$form->populate($res[0]);	
				}
						
				$this->view->form = $form;
			}
			else
			{
				$this->redirect('/');
			}
		}
		else
		{
			$this->_redirect('/');
		}
		
	}
	
	
	
	/*
	 * Delete a post
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function deleteAction()
	{
		// param
		$uid 		= intval($this->_request->getParam('uid', 0));
		
		// helper
		$url		= new Zend_View_Helper_Url();
		$baseUrl	= new MHDEV_View_Helper_BaseUrl();
		$isMod		= new MHDEV_View_Helper_IsMod();
		
		// db
		$posts		= new Posts();
		$threads	= new Threads();
		$user		= new User();
		$boards		= new Boards();
		
		// query
		$query		= $posts->find($uid);
		
		if($query->count() > 0)
		{
			$res = $query->toArray();
			
			$getTopic 	= $threads->find($res[0]['thread_uid']);
			$resTopic 	= $getTopic->toArray(); 
			
			if(
				$this->auth->hasIdentity() &&  
				$isMod->IsMod($this->auth->getIdentity()->uid, $resTopic[0]['board_uid'])
			) 
			{
				if($this->_request->isPost())
				{
					$del 	= $this->_request->getPost('del');
					
					if ($del == '' . Zend_Registry::get('lang')->_('post_delete_yes') . '') 
					{
						if($posts->update(array('is_deleted' => 1), 'uid=' . $uid))
						{
							// update user posts (-1)
							$user->update(array('count_posts' => new Zend_Db_Expr('count_posts-1')), 'uid=' . $res[0]['user_uid']);
							
							// update thread replies (-1)
							$threads->update(array('count_replies' => new Zend_Db_Expr('count_replies-1')), 'uid=' . $res[0]['thread_uid']);
							
							// update board posts (-1)
							$boards->update(array('count_posts' => new Zend_Db_Expr('count_posts-1')), 'uid=' . $resTopic[0]['board_uid']);
							
							// check if board is a sub board
							$rootCheck	= $boards->find($resTopic[0]['board_uid']);
							if($rootCheck->count() > 0)
							{
								// array with database results
								$arrayRootCheck = $rootCheck->toArray();
								
								// have a root uid?
								if($arrayRootCheck[0]['root_uid'] > 0)
								{
									// update root board
									$boards->update(array('count_posts' => new Zend_Db_Expr('count_posts-1')), 'uid =' . $arrayRootCheck[0]['root_uid']);
								}
							}
			
							// redirect to the thread
							$this->_redirect('/posts/' . $res[0]['thread_uid'] . '.html');
						}
					}
					else
					{
						if($posts->update(array('is_deleted' => 0), 'uid=' . $uid))
						{
							// update user posts (+1)
							$user->update(array('count_posts' => new Zend_Db_Expr('count_posts+1')), 'uid=' . $res[0]['user_uid']);
							
							// update thread replies (+1)
							$threads->update(array('count_replies' => new Zend_Db_Expr('count_replies+1')), 'uid=' . $res[0]['thread_uid']);
							
							// update board posts (+1)
							$boards->update(array('count_posts' => new Zend_Db_Expr('count_posts+1')), 'uid=' . $resTopic[0]['board_uid']);
							
							// check if board is a sub board
							$rootCheck	= $boards->find($resTopic[0]['board_uid']);
							if($rootCheck->count() > 0)
							{
								// array with database results
								$arrayRootCheck = $rootCheck->toArray();
								
								// have a root uid?
								if($arrayRootCheck[0]['root_uid'] > 0)
								{
									// update root board
									$boards->update(array('count_posts' => new Zend_Db_Expr('count_posts+1')), 'uid =' . $arrayRootCheck[0]['root_uid']);
								}
							}
							
							// redirect to thread
							$this->_redirect('/posts/' . $res[0]['thread_uid'] . '.html');
						}
					}
				}
			}
			else
			{
				$this->redirect('/');
			}
			
			$this->view->result = $res;
		}
		else
		{
			$this->_redirect('/');
		}
	}
	
	
	
	/*
	 * Report a post and create a ticket
	 * 
	 * @param null
	 * 
	 * @return void
	 */
	public function reportAction()
	{
		
	}
	
	
	
	/*
	 * Changes the mode of a topic
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public function modeAction()
	{
		// param
		$board_uid 	= intval($_POST['board_uid']);
		$thread_uid	= intval($this->_request->getParam('uid', 0));
		
		// db
		$threads	= new Threads();
		$boards		= new Boards();
		$posts		= new Posts();
		
		// helper
		$check		= new MHDEV_View_Helper_IsMod();
		$baseUrl	= new MHDEV_View_Helper_BaseUrl();
		$url		= new Zend_View_Helper_Url();
		
		if($this->auth->hasIdentity() && $check->IsMod($this->auth->getIdentity()->uid, $board_uid))
		{
			$modes		= array('open', 'close', 'sticky', 'unsticky', 'delete', 'undelete');
			$query 		= $threads->find($thread_uid);
			$getPosts 	= $posts->fetchAll('is_deleted = 0 AND thread_uid =' . $thread_uid);
			
			if($query->count() > 0)
			{
				$thread = $query->toArray();

				if(in_array($_POST['mod'][0], $modes))
				{
					switch ($_POST['mod'][0])
					{
						case 'open':
							// update thread
							$threads->update(array('is_closed' =>  0), 'uid=' . $thread_uid);
							
							// log
							$this->registry->get('log')->info('[MODERATE] Topic with ID ' . $thread_uid . ' (' . $thread[0]['title'] . ') is now open. Admin: ' . $this->auth->getIdentity()->uid);
						break;
						case 'close':
							// update thread
							$threads->update(array('is_closed' => 1), 'uid=' . $thread_uid);
							
							// log
							$this->registry->get('log')->info('[MODERATE] Topic with ID ' . $thread_uid . ' (' . $thread[0]['title'] . ') is now closed. Admin: ' . $this->auth->getIdentity()->uid);
						break;
						case 'sticky':
							// update thread
							$threads->update(array('is_sticky' => 1), 'uid=' . $thread_uid);
							
							// log
							$this->registry->get('log')->info('[MODERATE] Topic with ID ' . $thread_uid . ' (' . $thread[0]['title'] . ') is now sticky. Admin: ' . $this->auth->getIdentity()->uid);
						break;
						case 'unsticky':
							// update thread
							$threads->update(array('is_sticky' => 0), 'uid=' . $thread_uid);
							
							// log
							$this->registry->get('log')->info('[MODERATE] Topic with ID ' . $thread_uid . ' (' . $thread[0]['title'] . ') is now unsticky. Admin: ' . $this->auth->getIdentity()->uid);
						break;
						case 'delete':
							// update thread
							$threads->update(array('is_deleted' => 1), 'uid=' . $thread_uid);
							
							// update board
							$boards->update(array('count_posts' => new Zend_Db_Expr('count_posts-' . $getPosts->count()), 'count_threads' => new Zend_Db_Expr('count_threads-1')), 'uid =' . $board_uid);
							
							// check if board is a sub-board
							$rootCheck	= $boards->find($board_uid);
							if($rootCheck->count() > 0)
							{
								// array with database results
								$arrayRootCheck = $rootCheck->toArray();
								
								// have a root uid?
								if($arrayRootCheck[0]['root_uid'] > 0)
								{
									// update root board
									$boards->update(array('count_posts' => new Zend_Db_Expr('count_posts-' . $getPosts->count()), 'count_threads' => new Zend_Db_Expr('count_threads-1')), 'uid =' . $arrayRootCheck[0]['root_uid']);
								}
							}
							
							// log
							$this->registry->get('log')->info('[MODERATE] Topic with ID ' . $thread_uid . ' (' . $thread[0]['title'] . ') is now marked as deleted. Admin: ' . $this->auth->getIdentity()->uid);
						break;
						case 'undelete':
							// update thread
							$threads->update(array('is_deleted' => 0), 'uid=' . $thread_uid);
							
							// update board
							$boards->update(array('count_posts' => new Zend_Db_Expr('count_posts+' . $getPosts->count()), 'count_threads' => new Zend_Db_Expr('count_threads+1')), 'uid =' . $board_uid);
							
							// check if board is a sub-board
							$rootCheck	= $boards->find($board_uid);
							if($rootCheck->count() > 0)
							{
								// array with database results
								$arrayRootCheck = $rootCheck->toArray();
								
								// have a root uid?
								if($arrayRootCheck[0]['root_uid'] > 0)
								{
									// update root board
									$boards->update(array('count_posts' => new Zend_Db_Expr('count_posts+' . $getPosts->count()), 'count_threads' => new Zend_Db_Expr('count_threads+1')), 'uid =' . $arrayRootCheck[0]['root_uid']);
								}
							}
							
							// log
							$this->registry->get('log')->info('[MODERATE] Topic with ID ' . $thread_uid . ' (' . $thread[0]['title'] . ') is no more marked as deleted. Admin: ' . $this->auth->getIdentity()->uid);
						break;
					}
				}
			
				return $this->_redirect('/posts/' . $thread_uid . '.html');
			}
		}
		else
		{
			return $this->_redirect('/');
		}
	}
	
	
	
	/*
	 * init the bbcode-editor
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public function initEditor()
	{
		$baseurl = new MHDEV_View_Helper_BaseUrl();
		#$this->view->headScript()->appendScript('var basePath = \'' . $baseurl->BaseUrl() . '\';');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/editor.js');
	}
	
	
	
	/*
	 * Calculate the activity points
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	private function activityPoints()
	{
		// param
		$uid 	= $this->auth->getIdentity()->uid;
		
		// helper
		$datetime = new MHDEV_View_Helper_Datetime();
		
		// db
		$user 	= new User();
		
		// query
		$query	= $user->find($uid);
		
		if($query->count() > 0)
		{
			$res = $query->toArray();
			
			$dateArray 	= explode('.', $datetime->datetime($res[0]['create_date'], 'dd.MM.yy'));
			$timestamp	= mktime(0, 0, 0, $dateArray[1], $dateArray[0], $dateArray[2]); 
			
			$days_registered 	= round((time()-$timestamp)/60/60/24);
			$posts				= $res[0]['count_posts'];
			
			// Get Activity-Points
			$f1 		= round($days_registered*2/exp(pi())+1);
			$f2 		= round($posts*exp(1)/3);
			$points		= $f1*$f2;
			
			// Update Activity-Points
			$user->update(array(
				'activity_points' => $points
			), 'uid=' . $uid);
		}	
	}
	
	
	
	/*
	 * Updates the visit table
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	private function updateVisit($uid)
	{
		// db 
		$threadsVisit 	= new ThreadsVisit();
		
		if($this->auth->hasIdentity())
		{
			$checkVisit = $threadsVisit->fetchAll('thread_uid=' . $uid . ' AND user_uid=' . $this->auth->getIdentity()->uid);

			if($checkVisit->count() > 0)
			{
				$resVisit = $checkVisit->toArray();
				$threadsVisit->update(array(
					'date' => new Zend_Db_Expr('NOW()')
				), 'uid=' . $resVisit[0]['uid']);
			}
			else
			{
				$threadsVisit->insert(array(
					'user_uid'		=> $this->auth->getIdentity()->uid,
					'thread_uid'	=> $uid,
					'date'			=> new Zend_Db_Expr('NOW()'),
				));
			}
		}
	}
	
	
	
	/*
	 * Redirect to the last post of a thread
	 * 
	 * @param null
	 * 
	 * @return Zend_View
	 */
	public function getlastpostAction()
	{
		// params
		$uid 		= intval($this->getRequest()->getParam('uid', 0));
		$page 		= intval($this->getRequest()->getParam('page', 0));
		$count		= $this->auth->hasIdentity() ? $this->auth->getIdentity()->posts_per_page : $this->settings['posts_per_page'];
		
		// helper
		$url		= new Zend_View_Helper_Url();
		
		// db
		$posts		= new Posts();
		
		// query
		$select = $posts->select()->setIntegrityCheck(false);
		$select->from(
				array('p' => 'posts')
			)
			->join(
				array('u' => 'user'), 'u.uid = p.user_uid', array('username', 'count_threads', 'count_posts', 'signature')
			)
			->join(
				array('t' => 'threads'), 't.uid = p.thread_uid', array('is_deleted AS tdeleted')
			)
			->where('p.thread_uid = ?', $uid)
			->order('p.create_date ASC');
		
		// filter
		if(!$this->auth->hasIdentity() OR $this->auth->getIdentity()->role != 'admin')
		{
			$select->where('p.is_deleted = ?', 0);
			$select->where('t.is_deleted = ?', 0);
			$select->where('p.is_public = ?', 1);
		}
		
		$query		= $posts->fetchAll($select, null, $count);
		
		$getLastPost	= $posts->fetchAll('is_deleted = 0 AND is_public = 1 AND thread_uid =' . $uid, 'create_date DESC', 1);
		$arrLastPost	= $getLastPost->toArray();
		
		// paginator
		$paginator	= Zend_Paginator::factory($query->toArray());
        $paginator->setItemCountPerPage($count);
        $paginator->setCurrentPageNumber($page);
        
        $page			= $paginator->count();
        $redirect_url	= $url->url(array('controller' => 'posts', 'uid' => $uid, 'page' => $page), 'threads_p2', true);
        
		$this->_redirect('/posts/' . $uid . '-' . $page . '.html#post' . $arrLastPost[0]['uid']);
	}
	
	
	
	/*
	 * Get the current page number of a thread
	 * 
	 * @param int $thread_uid
	 * 
	 * @return int page_number
	 */
	private function getPageNumber($thread_uid)
	{
		// params
		$count		= $this->auth->hasIdentity() ? $this->auth->getIdentity()->posts_per_page : $this->settings['posts_per_page'];

		// db
		$posts		= new Posts();
		
		// query
		$select = $posts->select()->setIntegrityCheck(false);
		$select->from(
				array('p' => 'posts')
			)
			->join(
				array('u' => 'user'), 'u.uid = p.user_uid', array('username', 'count_threads', 'count_posts', 'signature')
			)
			->join(
				array('t' => 'threads'), 't.uid = p.thread_uid', array('is_deleted AS tdeleted')
			)
			->where('p.thread_uid = ?', $thread_uid)
			->order('p.create_date ASC');
		
		// filter
		if(!$this->auth->hasIdentity() OR $this->auth->getIdentity()->role != 'admin')
		{
			$select->where('p.is_deleted = ?', 0);
			$select->where('t.is_deleted = ?', 0);
			$select->where('p.is_public = ?', 1);
		}
		
		$query			= $posts->fetchAll($select, null, $count);

		// paginator
		$paginator	= Zend_Paginator::factory($query->toArray());
        $paginator->setItemCountPerPage($count);
        $paginator->setCurrentPageNumber($page);
        
        $page			= $paginator->count();
		
        return $page;
	}
	
	
	/*
	 * Update the status of a watched topic
	 * 
	 * @param int $uid
	 * 
	 * @return null
	 */
	private function observeThread($uid)
	{
		// vars
		$where_clause	= 'thread_uid = ' . intval($uid) . ' AND user_uid = ' . $this->auth->getIdentity()->uid;
		
		// db
		$thread			= new ThreadsNotice();
		
		// query
		$getThread		= $thread->fetchAll($where_clause);
		
		// check
		if($getThread->count() > 0)
		{
			$thread->update(array('last_post' => new Zend_Db_Expr('NOW()')), $where_clause);
		}
	}
	
	
	
	/*
	 * Set a post public
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public function setpublicAction()
	{
		// helper
		$mod		= new MHDEV_View_Helper_IsMod();
		
		// params
		$uid		= $this->_request->getParam('uid', 0);
		
		// db
		$posts		= new Posts();
		$threads	= new Threads();
		
		// query
		$getPost	= $posts->find($uid);
		
		// check if post is not yet deleted ...
		if($getPost->count() > 0)
		{
			$resPost	= $getPost->toArray();

			$getThread	= $threads->find($resPost[0]['thread_uid']);
			
			// get thread of this post ...
			if($getThread->count() > 0)
			{
				$resThread	= $getThread->toArray();
				
				// is this user a mod or a admin?!
				if($mod->IsMod($this->auth->getIdentity()->uid, $resThread[0]['board_uid']))
				{
					$posts->update(array('is_public' => 1), 'uid = ' . intval($uid));
					$this->_redirect('/threads/last_post-' . $resPost[0]['thread_uid'] . '.html');
				}
				else
				{
					$this->_redirect('/');
				}
			}
			else
			{
				$this->_redirect('/');
			}
		}
		else
		{
			$this->_redirect('/');
		}
	}
}
?>